package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    //查询
    @Override
    public List<Category> findAll() {
        return categoryMapper.findAll();
    }

    //新增
    @Override
    public void save(Category category) {
        //1.补全属性
        category.setId(IdUtil.getSnowflake(1, 1).nextId());
        /*category.setCreateTime(new Date());
        category.setUpdateTime(new Date());
        category.setCreateUser(1L);
        category.setUpdateUser(1L);*/
        //2.保存
        categoryMapper.save(category);
    }

    //修改
    @Override
    public void update(Category category) {
        categoryMapper.updateById(category);
    }

    //删除
    @Override
    public ResultInfo delete(Long id) {
        //1. 从菜品表中根据分类id统计菜品数量,如果数量>0,返回错误
        Integer count1 = categoryMapper.countDishByCategoryId(id);
        if (count1 > 0) {
            throw new CustomException("当前分类下存在菜品,不允许删除");
        }

        //2. 从套餐表中根据分类id统计套餐数量,如果数量>0,返回错误
        Integer count2 = categoryMapper.countSetmealByCategoryId(id);
        if (count2 > 0) {
            throw new CustomException("当前分类下存在套餐,不允许删除");
        }

        //3.分类删除
        categoryMapper.delete(id);

        //4.返回成功标识
        return ResultInfo.success(null);
    }

    @Override
    public List<Category> findByType(Integer type) {
        //设置查询条件
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getType, type);//where type = 1

        //执行查询
        return categoryMapper.selectList(wrapper);
    }

}
